import './public-path'
import { createApp } from 'vue'
import App from './App.vue'
import routes from './router'
import { createRouter, createWebHistory } from 'vue-router'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper';
import {pinia, useGlobalStore, useUserStore}  from '@glz/utils'
import { PROJECT_KEY } from './config'

let router = null;
let instance = null;
let history = null;


function render(props = {}) {
    const { container } = props;
    instance = createApp(App);
   
    history = createWebHistory(qiankunWindow.__POWERED_BY_QIANKUN__ ? '/vite-js/' : '/') // url 相對路徑
    router = createRouter({
        history,
        routes
    })
    
    instance.use(router);
    instance.use(pinia);
    instance.mount(container ? container.querySelector('#app') : document.getElementById("app"));
}

renderWithQiankun({
    mount(props) {
        console.log(PROJECT_KEY,'傳入props:',props)
        render(props);
        // 通讯api挂在在原型链上
        //instance.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange;
        //instance.config.globalProperties.$setGlobalState = props.setGlobalState;
        // 设置通信所需要的信息
        // props.onGlobalStateChange((state:any) => {
        //     store.commit('userinfo/setuserinfo', state.userinfo)
        //     store.commit('paramsinfo/setparamsinfo', state.paramsinfo)
        // },true)

        //const store_global = useGlobalStore(PROJECT_KEY)
        //store_global.setGlobalActions(props.actions)

        const store_user = useUserStore(PROJECT_KEY)

        store_user.setUser(props.data)

        //设置主应用传入的回调方法
        store_user.setRemoteUpdater(props.setUser)

        props.onChangeStore?.((store) =>{
            console.log(PROJECT_KEY,"store",store)
            store_user.setUser(store)
        })
        
    },
    bootstrap() {},
    unmount(props) {
        const store_user = useUserStore(PROJECT_KEY);
        store_user.delUser();

        store_user.clearUserChange();

        instance.unmount();
        //instance._container.innerHTML = '';
        history.destroy();
        router = null;
        instance = null;
    },
    update(props) {
        
    },
});
    

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
    console.warn(PROJECT_KEY, '子應用單獨訪問');
  render({})
  //阻止子應用獨立啟動
  //console.warn('子應用禁止單獨訪問');
  //location.href = "/"
  
 
}